<!doctype html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>EDA Copilot</title>
		<script src="/iframe/js/AI.js"></script>
		<script src="/iframe/js/marked.umd.js"></script>
		<link rel="stylesheet" href="/iframe/css/style.css" />
	</head>
	<body>
		<!-- 设置浮框 -->
		<div class="settings-container" id="settingsModal">
			<div class="settings-title">设置</div>
			<div class="settings-item" id="google-settings">
				<label class="settings-label" for="custom-google-host">接口地址:</label>
				<input type="text" class="settings-input" id="custom-google-host" />

				<label class="settings-label" for="google-api-key">API KEY:</label>
				<input type="text" class="settings-input" id="google-api-key" />

				<label class="settings-label" for="custom-google-header">自定义请求头:</label>
				<input type="text" class="settings-input" id="custom-google-header" />
			</div>
			<div class="settings-item" id="ds-settings" style="display: none">
				<label class="settings-label" for="custom-ds-host">接口地址:</label>
				<input type="text" class="settings-input" id="custom-ds-host" />

				<label class="settings-label" for="ds-api-key">API KEY:</label>
				<input type="text" class="settings-input" id="ds-api-key" />

				<label class="settings-label" for="custom-ds-header">自定义请求头:</label>
				<input type="text" class="settings-input" id="custom-ds-header" />
			</div>
			<div class="settings-item" id="qwen-settings" style="display: none">
				<label class="settings-label" for="custom-qwen-host">接口地址:</label>
				<input type="text" class="settings-input" id="custom-qwen-host" />

				<label class="settings-label" for="qwen-api-key">API KEY:</label>
				<input type="text" class="settings-input" id="qwen-api-key" />

				<label class="settings-label" for="custom-qwen-header">自定义请求头:</label>
				<input type="text" class="settings-input" id="custom-qwen-header" />
			</div>
			<div class="settings-item" id="custom-settings" style="display: none">
				<label class="settings-label" for="custom-host">接口地址:</label>
				<input type="text" class="settings-input" id="custom-host" />

				<label class="settings-label" for="custom-endpoint">终结点:</label>
				<input type="text" class="settings-input" id="custom-endpoint" />

				<label class="settings-label" for="custom-model">模型:</label>
				<input type="text" class="settings-input" id="custom-model" />

				<label class="settings-label" for="custom-header">自定义请求头:</label>
				<input type="text" class="settings-input" id="custom-header" />
			</div>
			<div class="settings-buttons">
				<button class="settings-button cancel" onclick="closeSettings()">取消</button>
				<button class="settings-button save" onclick="saveSettings()">保存</button>
			</div>
		</div>
		<!-- 模型浮框 -->
		<div class="settings-container" id="modelsModal">
			<div class="settings-title">模型</div>
			<div class="settings-item">
				<label class="settings-label" for="model-name">选择模型</label>
				<select class="settings-input" id="model-name">
					<optgroup label="Custom">
						<option value="custom">自定义</option>
					</optgroup>
					<optgroup label="Gemini">
						<option value="gemini-2.0-flash-001">gemini-2.0-flash</option>
						<option value="gemini-1.5-flash-002" selected>gemini-1.5-flash</option>
						<option value="gemini-1.5-pro-002">gemini-1.5-pro</option>
					</optgroup>
					<optgroup label="DeepSeek">
						<option value="deepseek-reasoner">deepseek-r1</option>
						<option value="deepseek-chat">deepseek-v3</option>
					</optgroup>
					<optgroup label="QWen">
						<option value="qwen-vl-max-latest">qwen-vl-max</option>
						<option value="qwen-max-latest">qwen-max</option>
						<option value="qwen-plus-latest">qwen-plus</option>
					</optgroup>
				</select>
			</div>
			<div class="settings-buttons">
				<button class="settings-button cancel" onclick="closeModels()">取消</button>
				<button class="settings-button save" onclick="saveModels()">保存</button>
			</div>
		</div>
		<!-- 主体 -->
		<div class="chat-container">
			<!-- header -->
			<div class="chat-header">
				<div class="chat-title" id="title">新的聊天</div>
				<div class="chat-subtitle" id="subtitle">测试</div>
			</div>
			<!-- body -->
			<div class="chat-body">
				<div class="message-bubble">
					<div>有什么可以帮你的吗？</div>
					<div class="message-meta">预设提示词</div>
				</div>
			</div>
			<!-- footer -->
			<div class="chat-footer">
				<!-- 图片显示框 -->
				<div class="paste-image-group">
					<div id="paste-image-delete-btn"></div>
					<div id="paste-image"></div>
				</div>
				<!-- 按钮们 -->
				<div class="icon-group">
					<button id="getNetList">
						<span class="button-tip">解析网表</span>
						<img
							src=""
							alt="解析网表"
						/>
					</button>
					<button id="addFile">
						<span class="button-tip">添加文件</span>
						<img
							src=""
							alt="添加文件"
						/>
					</button>
					<button id="newChat">
						<span class="button-tip">新的聊天</span>
						<img
							src=""
							alt="新的聊天"
						/>
					</button>
					<button id="model">
						<span class="button-tip">模型</span>
						<img
							src=""
							alt="设置"
						/>
					</button>
					<button id="setting">
						<span class="button-tip">设置</span>
						<img
							src=""
							alt="设置"
						/>
					</button>
					<button id="test" style="display: none">
						<span class="button-tip">测试</span>
						<img
							src=""
							alt="测试"
						/>
					</button>
				</div>
				<!-- 消息输入框 -->
				<div class="input-group">
					<input type="text" class="chat-input" id="chat-input" placeholder="解析网表后可以解决复杂问题" />
					<button class="send-button" id="send">发送</button>
				</div>
			</div>
		</div>

		<script>
			// 测试网络连接
			eda.sys_ClientUrl
				.request('https://lceda.cn', 'GET')
				.then((response) => {
					// ok!!
				})
				.catch((error) => {
					eda.sys_Message.showToastMessage('本拓展需要启用外部交互权限！', 'error');
				});
		</script>

		<script src="/iframe/js/main.js"></script>

		<script>
			document.getElementById('getNetList').addEventListener('click', function () {
				getNetlist();
			});

			document.getElementById('addFile').addEventListener('click', function () {
				setAIFile();
			});

			document.getElementById('model').addEventListener('click', function () {
				openModels();
			});

			document.getElementById('setting').addEventListener('click', function () {
				openSettings();
			});

			document.getElementById('newChat').addEventListener('click', function () {
				chatHistory = [];
				let clearChat = document.createElement('div');
				clearChat.className = 'clear-chat';
				clearChat.innerHTML = '上下文已清除';
				document.querySelector('.chat-body').appendChild(clearChat);
				document.querySelector('.chat-body').scrollTop = document.querySelector('.chat-body').scrollHeight;
				CHAT_TITLE = '新的聊天';
				document.getElementById('title').innerText = CHAT_TITLE;
			});

			document.getElementById('test').addEventListener('click', function () {
				getDatasheetUrl().then((url) => {
					console.log(url);
					getDatasheetData(url).then((data) => {
						console.log(data);
					});
				});
			});

			document.getElementById('chat-input').addEventListener('keypress', function (event) {
				if (event.key === 'Enter') {
					event.preventDefault();
					document.getElementById('send').click();
				}
			});

			document.getElementById('send').addEventListener('click', function () {
				let input = document.getElementById('chat-input');
				let showImage = false;
				let image = null;
				let message = input.value;
				if (!message) return;
				if (MODEL_GROUP === 'Gemini') {
					let parts = [{ text: message }];
					image = document.getElementById('paste-image').style.backgroundImage;
					image = image.replace('url("', '').replace('")', '').replace('data:image/png;base64,', '');
					if (image) {
						showImage = true;
						parts.push({ inline_data: { mime_type: 'image/png', data: image } });
						document.getElementById('paste-image').style.backgroundImage = '';
						document.getElementsByClassName('paste-image-group')[0].style.display = 'none';
					}

					if (FILE_BASE64 !== null) {
						parts.push({ inline_data: { mime_type: 'application/pdf', data: FILE_BASE64 } });
						FILE_BASE64 = null;
					}
					chatHistory.push({ role: 'user', parts: parts });
				} else if (MODEL_GROUP === 'DeepSeek' || (MODEL_GROUP === 'QWen' && MODEL_NAME !== 'qwen-vl-max-latest')) {
					chatHistory.push({ role: 'user', content: message });
				} else if (MODEL_GROUP === 'Custom' || (MODEL_GROUP === 'QWen' && MODEL_NAME === 'qwen-vl-max-latest')) {
					let contents = [];
					image = document.getElementById('paste-image').style.backgroundImage;
					image = image.replace('url("', '').replace('")', '').replace('data:image/png;base64,', '');
					if (image) {
						showImage = true;
						contents.push({ type: 'image_url', image_url: { url: 'data:image/png;base64,' + image } });
						document.getElementById('paste-image').style.backgroundImage = '';
						document.getElementsByClassName('paste-image-group')[0].style.display = 'none';
					}
					contents.push({ type: 'text', text: message });
					chatHistory.push({ role: 'user', content: contents });
				}

				createBubble('user', message + (showImage ? `\n![图片](data:image/png;base64,${image})` : ''), undefined);
				input.value = '';
				getAIResponse(chatHistory);
			});

			document.addEventListener('paste', function (event) {
				const items = (event.clipboardData || window.clipboardData).items;
				for (let i = 0; i < items.length; i++) {
					if (items[i].type.indexOf('image') !== -1) {
						const blob = items[i].getAsFile();
						const reader = new FileReader();
						reader.onload = function (event) {
							const pasteImage = document.getElementById('paste-image');
							if (pasteImage) {
								pasteImage.parentElement.style.display = 'block';
								pasteImage.style.backgroundImage = `url(${event.target.result})`;
							}
						};
						reader.readAsDataURL(blob);
					}
				}
			});

			document.getElementById('paste-image-delete-btn').addEventListener('click', function () {
				const pasteImage = document.getElementById('paste-image');
				if (pasteImage) {
					pasteImage.parentElement.style.display = 'none';
					pasteImage.style.backgroundImage = '';
				}
			});
		</script>

		<script>
			// 测试用的代码
			let clickCount = 0;
			let isTestMode = false;
			const settingButton = document.getElementById('setting');
			const testButton = document.getElementById('test');

			settingButton.addEventListener('click', () => {
				clickCount++;
				if (isTestMode) {
					eda.sys_Message.showToastMessage('已经处于测试模式', 'info');
					return;
				}
				if (!isTestMode) {
					if (clickCount === 5) {
						eda.sys_Message.showToastMessage('已进入测试模式', 'info');
						testButton.style.display = 'block';
						isTestMode = true;
						clickCount = 0;
					}
					if (clickCount === 3) {
						eda.sys_Message.showToastMessage('再点击2次进入测试模式', 'info');
					}
					if (clickCount === 4) {
						eda.sys_Message.showToastMessage('再点击1次进入测试模式', 'info');
					}
					setTimeout(() => {
						clickCount = 0;
					}, 4000);
				}
			});
		</script>
	</body>
</html>
